package com.wifi.user.servlet;

import com.alibaba.fastjson.JSON;
import com.wifi.unti.LoginUtil;
import com.wifi.user.entity.Menu;
import com.wifi.user.entity.User;
import com.wifi.user.service.MenuService;
import com.wifi.user.service.MenuServiceImpl;
import com.wifi.user.service.UserService;
import com.wifi.user.service.UserServiceImpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    UserService userService = new UserServiceImpl();
MenuService menuService=new MenuServiceImpl() ;
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/login.jsp").forward(request, response);
//        response.getWriter().write("<script>alert("+"用户名或密码错误请重输"+")</script>");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String pwd = request.getParameter("password");
        LoginUtil loginUtil = new LoginUtil();
        String pwdMD5 = loginUtil.encroMD5(pwd);
        Object o = userService.login(new User(), username, pwdMD5);
        User u = (User) o;
        if (o == null || u.getVlid() != 0) {
request.getSession().setAttribute("errorMsg","账号或密码错误，请重新登录");
            doGet(request, response);
        } else {
            int id = u.getId();
            int i = userService.setLoginDate(id);
            if (i > 0) {
                List<Object> menu= menuService.getMenu(id);
                u.setLastLoginTime(new Timestamp(new Date().getTime()));
                request.getSession().setAttribute("menu",menu);
                request.getSession().setAttribute("user", u);
                System.out.println(JSON.toJSONString(u));
                System.out.println(JSON.toJSONString(menu));
//                response.getWriter().write(JSON.toJSONString(u));
                request.getRequestDispatcher("/index.jsp").forward(request, response);
            } else {request.getSession().setAttribute("errorMsg","服务器维护中，稍后登录");
                doGet(request, response);
            }
        }
    }
}
